package com.starblink.brand.adapter

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.VibrateUtils
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.ext.load
import com.starblink.basic.log.SKLogger
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.brand.databinding.ItemBrandProduct2Binding
import com.starblink.library.widget.product.pop.GoodsFindSimilarPop
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.fragment.ProductD
import com.starblink.rocketreserver.fragment.ProductF
import kotlinx.coroutines.MainScope

@Deprecated(message = "已废弃 1.15.2")
class BrandCollectionCardView2 @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0
) : ConstraintLayout(context, attrs, defStyleRes) {
    companion object {
        const val TAG = "ProductCardView"
        const val RATIO_LIMIT = 9F / 16F
    }

    lateinit var product: ProductF
    lateinit var  mActivity: FragmentActivity

    val binding: ItemBrandProduct2Binding = ItemBrandProduct2Binding.inflate(inflater, this, true)

    private var pageDef: Int = SpmPageDef.BrandDetailPage
    var position: Int = 0
    var firstTraceInfo: String? = ""

    private val strOn = CommUtils.getString(R.string.on)
    private val strWishPeople = CommUtils.getString(R.string.people_wish)
    private val collectImg = R.mipmap.ic_prd_collect
    private val collectedImg = R.mipmap.ic_prd_collected
    private val theScope get() = (context as? AppCompatActivity?)?.lifecycleScope ?: MainScope()
    private val findSimilarPop by lazyOnNone {
        GoodsFindSimilarPop(context) {
            doCollectGoods()
        }
    }

    fun bindModel(
        mActivity: FragmentActivity,
        model: ProductF,
        position: Int,
        brandName:String?,
        compareCall: (ProductF) -> Unit
    ) {
        this.product = model
        this.mActivity=mActivity
        this.position=position

        //划线价格处理 折扣
        val disCountInfo = model.disCountInfo
        //品牌logo和name
        val merchantWebVOF = model.merchantWeb

        binding.ivProduct.run {
            updateLayoutParams<LayoutParams> {
                this.dimensionRatio =
                    if (model.mainPicSize.isNullOrEmpty()) "1" else model.mainPicSize?.let {
                        var ratio = 1f
                        try {
                            ratio = it.split("*").let { list ->
                                list[0].toFloat() / list[1].toFloat()
                            }
                        } catch (e: Exception) {
                            SKLogger.e(TAG, e.message ?: "mainPicSize parse erro")
                        }
                        if (ratio.isNaN()) {
                            ratio = 1f
                        }
                        if (ratio < RATIO_LIMIT) {
                            ratio = RATIO_LIMIT
                        }
                        ratio.toString()
                    }
            }
            load(model.mainImg)
            // ivProduct注册了长按事件消费，需要单独处理点击
            click {
                this@BrandCollectionCardView2.performClick()
            }
        }

        binding.ivBrandLogo.load(merchantWebVOF?.logo, merchantWebVOF?.merchantName)
        binding.brandTxt.text=brandName?:""
        //是否订阅店铺
        binding.brandImgColl.setImageResource(if (merchantWebVOF?.subOrNot == true) com.starblink.android.common.R.mipmap.icon_web_followed else com.starblink.android.common.R.mipmap.icon_web_follow)

        //标题
        if (model.title.isNullOrBlank()) {
            binding.tvName.gone()
        } else {
            binding.tvName.visible()
            binding.tvName.text = model.title
        }
        //处理前台属性
        if (model.frontPropertyList.isNullOrEmpty()) {
            binding.tvFrontAttr.gone()
        } else {
            binding.tvFrontAttr.visible()
            var attrString = ""
            var tag1 = 0
            model.frontPropertyList?.forEach { property ->
                if (tag1 == model.frontPropertyList!!.size - 1) {
                    property.value?.let {
                        attrString += it
                    }
                } else {
                    property.value?.let {
                        attrString += "$it | "
                    }
                }
                tag1++
            }
            if (attrString.isEmpty()) {
                binding.tvFrontAttr.gone()
            } else {
                binding.tvFrontAttr.text = attrString
            }
        }
        //价格
        if ((model.price ?: 0.0) > 0) {
            binding.tvPrice.visible()
            binding.tvPrice.show(
                model.price!!,
                model.currency,
                model.currencySymbol
            )
        } else {
            binding.tvPrice.gone()
        }

        if (disCountInfo != null) {
            binding.tvPriceDiscount.visibleOrGone(disCountInfo.discountText?.isNotEmpty() == true && disCountInfo.underlinePrice != null) {
                disCountInfo.underlinePrice?.let {
                    binding.tvPriceDiscount.show(
                        it,
                        model.currency,
                        model.currencySymbol
                    )
                }
            }
            //折扣tag
            binding.tvDiscountTag.visibleOrGone(true) {
                text = "-${disCountInfo.discountPercent}"
            }
        }
        //on XX people\'s wishlists
//        binding.tvVoteNum.visibleOrGone((model.voteNum ?: 0) > 0){
//            text = "$strOn ${model.voteNum} $strWishPeople"
//        }
        //设置收藏tag
        binding.btnAddToBoard.tag = model.id
        //是否收藏商品
        updateCollect(model.collected)

        //订阅店铺
        binding.brandImgColl.run  {
            //文档上没有写埋点
//            trackData(
//                page = pageDef,
//                element = SpmElementDef.StoreSub,
//                traceInfo = traceInfo(),
//                onlyHit = true,
//                params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
//                    .plus("result" to "${if (merchantWebVOF?.subOrNot == true) "0" else "1"}")
//            )
            click {
                doSubscribeStore()
            }
        }

        binding.ivProduct.setOnLongClickListener {
            //长按找相似
            if (binding.ivProduct.drawable == null) return@setOnLongClickListener false
            VibrateUtils.vibrate(100L)
            if (model?.mainImg.isNullOrEmpty() || model?.id.isNullOrEmpty() || model?.type == null) {
                return@setOnLongClickListener false
            }

            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    params = SpmTrackHandler.trackProductMap(position, product!!),
                    traceInfo = product!!.traceInfo ?: "",
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        pageDef,
                        SpmElementDef.GOODS_CARD_FIND_SIMILAR,
                    ),
                )
            )

            findSimilarPop.showPopup(
                binding.ivProduct,
                model?.mainImg!!,
                model?.id!!,
                model?.type!!,
                add = model?.collected == true
            )
            true
        }

        binding.imgCollect.run {
            //收藏
            trackData(
                page = pageDef,
                element = SpmElementDef.ProductDetailNewBodyCollection,
                onlyHit = true,
                traceInfo = product.traceInfo,
                params = trackMap().plus(
                    "status" to (if (UserDataCenter.isLogin()) "1" else "0")
                )
                    .plus("result" to if (product.collected == true) "0" else "1")
            )
            click {
                doCollectGoods()
            }
            updateCollect(model.collected)
        }

        binding.llBrandBj.visibleOrGone(product.brotherOffers?.isNotEmpty() == true) {
            var logos = mutableListOf<String>()
            for (i in product.brotherOffers?.indices!!) {
                val brotherOffer = product.brotherOffers!![i]
                if (i < 3) {
                    brotherOffer?.brotherOfferF?.merchantWeb?.logo?.let { it1 -> logos.add(it1) }
                }
            }
            binding.flOtherStore.load(logos, borderColor = R.color.sk_gray50)
            val storeStr=if(product.brotherOffers?.size!! >1) "Stores" else "Store"
            binding.tvOtherStores.text="Check Other ${product.brotherOffers?.size} $storeStr"

            trackData(
                element = SpmElementDef.GOODS_CARD_OFFER_MORE_CLICK,
                page = pageDef,
                onlyHit = true,
                params = trackMap(),
                traceInfo = product!!.traceInfo
            )
            click { compareCall.invoke(product) }
        }

        trackData(
            page = pageDef,
            element = SpmElementDef.ProductDetailNewBody,
            traceInfo = product.traceInfo,
            showRatio = 0.9f,
            params = trackMap(),
            businessSuffixID = businessSuffixId(product)
        )

        initObservable()
    }

    //收藏商品
    private fun doCollectGoods() {
        product.id?.let { it1 ->
            CommonMutateManage.collectProduct(
                ctx = context,
                id = it1,
                type = product.type,
                collected = product.collected == true,
                scope = theScope,
                refreshState = {
                    updateCollect(product.collected?.not())
                },
                resultCallback = { it, collected ->
                    if (it) {
                        ApolloValSetExt.setApolloVal<ProductF>(
                            product,
                            "collected",
                            collected
                        )
                        binding.imgCollect.trackData(
                            page = pageDef,
                            element = SpmElementDef.ProductDetailNewBodyCollection, onlyHit = true,
                            params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                .plus("result" to "${if (product.collected == true) "0" else "1"}")
                        )
                        updateCollect(product.collected)
                        if (binding.btnAddToBoard.tag == product.id) {
                            binding.btnAddToBoard.visibleOrGone(product.collected == true) {//展示add board
                                FlowCountDownTimer(time = 2).start(callBack = {
                                }, onFinish = {
                                    binding.btnAddToBoard.visibleOrGone(false) {

                                    }
                                })
                                setOnClickListener {
                                    WishlistAddBottomDialog.showAddListDialog(
                                        context,
                                        batchPros = arrayListOf(
                                            BatchProductArrEntry(
                                                id = product.id ?: "",
                                                type = product.type,
                                                url = product.mainImg ?: ""
                                            )
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            )
        }
    }

    //订阅店铺
    private fun doSubscribeStore(){
        val merchantWebVOF = product.merchantWeb
        merchantWebVOF?.let { it1 ->
            CommonMutateManage.subscribeOrNotMerchant(
                context,
                merchantId = merchantWebVOF.id,
                merchantName = merchantWebVOF.merchantName,
                subOrNot = merchantWebVOF.subOrNot,
                resultCallback = {
                    if (it) {
                        product?.let { it2 ->
                            it2.merchantWeb?.let { it3 ->
                                ApolloValSetExt.setApolloVal<ProductD.MerchantWeb>(
                                    it3,
                                    "subOrNot",
                                    it1.subOrNot.not()
                                )
                            }
                        }
                        //文档上没有写埋点
//                        binding.brandImgColl.trackData(
//                            page = pageDef,
//                            element = SpmElementDef.StoreSub,
//                            traceInfo = traceInfo(),
//                            onlyHit = true,
//                            params = trackMap().plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
//                                .plus("result" to "${if (merchantWebVOF?.subOrNot == true) "0" else "1"}")
//                        )
                        updateFollow(it1.subOrNot)
                    }
                }
            )
        }
    }

    private fun updateCollect(collected: Boolean?) {
        binding.imgCollect.setImageResource(collected?.let {
            if (it) collectedImg else collectImg
        } ?: collectImg)
    }

    private fun updateFollow(followed: Boolean) {
        binding.brandImgColl.setImageResource(followed.let {
            if (it) com.starblink.android.common.R.mipmap.icon_web_followed else com.starblink.android.common.R.mipmap.icon_web_follow
        })
    }

    private fun trackMap() = SpmTrackHandler.trackProductMap(position, product)

    private fun initObservable(){
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == product.merchantWeb?.id && event.followed != product.merchantWeb?.subOrNot) {
                    product.merchantWeb?.apolloValue("subOrNot", event.followed)
                }
                product.offerList?.forEach {
                    if (event.id == it?.spuOffer?.merchantWeb?.id && event.followed != it?.spuOffer?.merchantWeb?.subOrNot) {
                        it?.spuOffer?.run {
                            this.merchantWeb?.apolloValue("subOrNot", event.followed)
                        }
                    }
                }
                binding.brandImgColl.setImageResource(if (product.merchantWeb?.subOrNot == true) com.starblink.android.common.R.mipmap.icon_web_followed else com.starblink.android.common.R.mipmap.icon_web_follow)
            }
        }
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == this.product?.id) {
                    this.product?.apolloValue("collected", event.collect)
                    updateCollect(this.product?.collected)
                }
                product.offerList?.forEach {
                    if (event.id == it?.spuOffer?.id) {
                        it?.spuOffer?.run {
                            apolloValue("collected", event.collect)
                        }
                    }
                }
            }
        }
    }

    private fun traceInfo() =
        if (position == 0 && firstTraceInfo?.isNotEmpty() == true) firstTraceInfo else product.traceInfo
}